import React from "react";
import { Spin } from "antd";

class Loading extends React.PureComponent {
  state = {
    loading: false,
  };

  start() {
    this.setState({
      loading: true,
    });
  }

  stop() {
    this.setState({
      loading: false,
    });
  }

  render() {
    const { loading } = this.state;
    return <Spin spinning={loading}>{this.props.children}</Spin>;
  }
}
const loadingRef = React.createRef();
export default function ExportPlugin() {
  return {
    commands: {
      export: editor => {
        const { value } = editor;
        const data = value.toJS();
        const element = document.createElement("a");
        element.setAttribute(
          "href",
          `data:application/json;charset=utf-8,${encodeURIComponent(
            JSON.stringify(data)
          )}`
        );
        element.setAttribute("download", "form.json");
        element.style.display = "none";
        document.body.appendChild(element);
        element.click();
        document.body.removeChild(element);
      },
      renderEditor: (props, editor, next) => {
        const children = next();
        return <Loading ref={loadingRef}>{children}</Loading>;
      },
    },
  };
}
